package com.xunji.user.util;

import cn.hutool.extra.spring.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;

public class PwdUtil {


    public static String encode(String pwd) {
        if (StringUtils.isNotEmpty(pwd)) {
            return SpringUtil.getBean(PasswordEncoder.class).encode(pwd);
        }
        return null;
    }

    /**
     * 密码是否有效。规则：大写字母，小写字母，数字，特殊符号至少包含三种
     *
     * @param password
     * @return
     */
    public static boolean effective(String password) {

        if (StringUtils.isEmpty(password)) {
            return false;
        }

        //1.全部包含：大写、小写、数字、特殊字符；
        String regex1 = "(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\\W_])^.*$";

        //2.无大写：小写、数字、特殊字符；
        String regex2 = "(?=.*[a-z])(?=.*[0-9])(?=.*[\\W_])^.*$";

        //3.无小写：大写、数字、特殊字符；
        String regex3 = "(?=.*[A-Z])(?=.*[0-9])(?=.*[\\W_])^.*$";

        //4.无数字：大写、小写、特殊字符；
        String regex4 = "(?=.*[A-Z])(?=.*[a-z])(?=.*[\\W_])^.*$";

        //5.无特殊字符：大写、小写、数字；
        String regex5 = "(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])^.*$";

        String regex = "(" + regex1 + ")|(" + regex2 + ")|(" + regex3 + ")|(" + regex4 + ")|(" + regex5 + ")";

        return password.matches(regex);

    }

    /**
     * 密码是否有效，规则（不包括特殊字符）：大写字母，小写字母，数字中，至少包含两种
     *
     * @param password password
     * @return boolean
     */
    public static boolean effectiveNew(String password) {
        if (StringUtils.isEmpty(password)) return false;
        //数字
        String REG_NUMBER = ".*\\d+.*";
        //小写字母
        String REG_UPPERCASE = ".*[A-Z]+.*";
        //大写字母
        String REG_LOWERCASE = ".*[a-z]+.*";
        //特殊符号
        String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";
        int i = 0;
        if (password.matches(REG_NUMBER)) i++;
        if (password.matches(REG_LOWERCASE)) i++;
        if (password.matches(REG_UPPERCASE)) i++;
        //if (password.matches(REG_SYMBOL)) i++;
        if (i < 2) return false;
        return true;
    }

}
